package com.kara.woodAgent.agent.graph.impl;

import com.kara.woodAgent.agent.graph.*;
import com.kara.woodAgent.agent.graph.communicate.*;

import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/5 13:40:13
 */
public class GraphNodeImpl<PGC extends GraphContext, SGC extends GraphContext> implements GraphNode<PGC> {


    private final BaseGraph<SGC> baseGraph;


    private Function<PGC, SGC> func;

    private BiFunction<PGC, SGC, Next> next;

    public GraphNodeImpl(BaseGraph<SGC> baseGraph) {
        this.baseGraph = baseGraph;
    }


    public GraphNodeImpl<PGC, SGC> gcSupplier(Function<PGC, SGC> func) {
        this.func = func;
        return this;
    }

    public GraphNodeImpl<PGC, SGC> next(BiFunction<PGC, SGC, Next> next) {
        this.next = next;
        return this;
    }


    @Override
    public Next execute(PGC context) {
        throw new RuntimeException("not implement");
    }

    @Override
    public Next executeGraph(PGC context, BaseRunningGraph<PGC> parentStep) {

        StepImage<SGC> image = null;
        Channel channel = context.getChannel();

        //当前已是受检状态,恢复子图
        if (context.getChannel().checking()) {
            ChannelMessage channelMessage = context.getChannel().resume();
            if (channelMessage instanceof TransmitMessage transmitMessage) {

//                String content = transmitMessage.getContent();
                image = transmitMessage.getImage();
//                image.setChannelMessage(ChannelMessage.from(content));
            } else {
                throw new RuntimeException("channelMessage not TransmitMessage");
            }
        }
        if (image == null) {
            image = baseGraph.createImage(func.apply(context));
        }


        RunningGraph<SGC> sgcStep = baseGraph.channelSupplier(channel::copy).build(image);
        sgcStep.communicate(parentStep.function)
                .then((response) -> parentStep.consumer.accept(response));

        sgcStep.start();
        //如果子图是受检状态 就把parent也改为受检状态
        if (sgcStep.checking()) {
            image = sgcStep.image();
            context.getChannel().checkpoint(new TransmitPayload(image));
        }

        return next.apply(context, (SGC) image.getContext());
    }
}
